import baseUrl from './config.js'
const headers = {}

const request = ({
	url,
	method,
	data,
	isNotHeader
}) => {
	let obj = {
		url: baseUrl + url, //仅为示例，并非真实接口地址。
		method: method || "GET",
	}
	if (data) {
		obj.data = data
	}
	//isNotHeader 是否需要请求头 ,如果是true，则表示不需要请求头
	if (!isNotHeader) {
		//获取请求头
		let token = uni.getStorageSync('storage_key')
		if (token) {
			headers['Authorization'] = "Bearer "+ token +""
			obj.header = headers
		}
	}
	return new Promise((resolve, reject) => {
		uni.request({
			...obj,
			success: (res) => {
				switch (res.statusCode) {
					case 200:
						return resolve(res.data)
					case 401:
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						})
						return reject(res)
					case 402:
						uni.showToast({
							title: '参数值不对',
							icon: 'none'
						})
						return reject(res)
					case 500:
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						})
						return reject(res)
					case 502:
						uni.showToast({
							title: '网站内部错误，请联系网站维护人员',
							icon: 'none'
						})
						return reject(res)
					default:
						uni.showToast({
							title: '请求异常',
							icon: 'none'
						})
						return reject(res);
				}
			},
			fail: (error) => {
				uni.showToast({
					title: '网站内部错误，请联系网站维护人员',
					icon: 'none'
				})
				reject(error)
			}
		});
	})
}
export default request
